/**
 * ChartObserver.java
 */
package com.pluginsacceptor.plugin.chart;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;

import com.pluginsacceptor.plugin.chart.impl.TableauEntierEtendu;
import com.pluginsacceptor.plugin.chart.model.ChartState;
import com.pluginsacceptor.plugin.chart.model.CurrentChartState;
import com.pluginsacceptor.utils.CommunicationUtils;

/**
 * The class contains method for update data from chart plugin
 */
public class ChartObserver implements Observer {

    /** Logger */
    private static final Logger LOG = Logger.getLogger(ChartObserver.class);

    /** */
    private final List<CurrentChartState> chartsState;

    /** */
    private final List<TableauEntierEtendu> tableDesIntiers;

    /**
     * Constructor
     */
    public ChartObserver(
        final List<CurrentChartState> state,
        final List<TableauEntierEtendu> tableDesIntiers
    ) {
        this.tableDesIntiers = tableDesIntiers;
        this.chartsState = state;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(final Observable arg0, final Object externalData) {

        if (externalData instanceof String) {
            final String cellString = (String) externalData;
            try {
                final int size = this.chartsState.size();
                for (int cnt = 0; cnt < size; cnt++) {
                    final CurrentChartState chartState = this.chartsState.get(cnt);
                    if (parseData(cellString, chartState)) {
                        this.tableDesIntiers.get(cnt).melange(chartState.getBarChartData());
                    }
                }
            } catch (final Exception e) {
                LOG.warn("Unexpected message format '" + cellString + "'", e);
            }
        }
    }

    /**
     * Parse source data string
     * @param cellString the source data string
     * @return <code>true</code> if data has been changed
     */
    private boolean parseData(final String cellString, final CurrentChartState state) {
        boolean isChanged = false;
        LOG.debug("Received data '" + cellString + "'");
        if (
            state.getChartState() == ChartState.RECEIVED_NEW_DATA
                && CommunicationUtils.isStartCellSelection(cellString)
        ) {
            state.getBarChartData().clean();
            isChanged = true;

//        } else if (CommunicationUtils.isEndCellSelection(cellString)) {

        } else if (CommunicationUtils.isCellData(cellString)) {
            isChanged = ChartUtils.changeChartData(cellString, state);
//            LOG.debug(
//                "Received data[ col: " + CommunicationUtils.getColNumFromCellString(cellString)
//                    + ", row: " + CommunicationUtils.getRowNumFromCellString(cellString)
//                    + ", value: " + CommunicationUtils.getValueFromCellString(cellString)
//            );
        }
        return isChanged;
    }

}
